//
//  UserAccount.swift
//  WeiBo
//
//  Created by 江潘 on 15/6/27.
//  Copyright © 2015年 江潘. All rights reserved.
//

import UIKit
import AFNetworking

// 要归档的类对象，类必须要遵守NSCoding协议
class UserAccount: NSObject,NSCoding {

    var access_token:String
    var expires_in:NSTimeInterval
    var uid:String
    var expiresDate:NSDate
    var name:String?
    var avatar_large:String?
    
    init(InfoDict:[String:AnyObject]) {
        access_token = InfoDict["access_token"] as!String
        expires_in = InfoDict["expires_in"] as!NSTimeInterval
        uid = InfoDict["uid"] as!String
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        name = InfoDict["name"] as?String
        avatar_large = InfoDict["avatar_large"] as?String
   }
    // 重写description方法，将打印模型中的内容
    override var description:String {
    
       let properties = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        
       return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    
    // swift中设置类常量用static
    
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("UserAccount.plist")
    
    func saveAccount(){
     // 类属性，要类来调用
       print("归档账户")
       print(UserAccount.accountPath)
       NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    // 解档可能为nil
    
    class func loadAccount()->UserAccount? {
        
      print("解档账户")
        
    //判断沙盒加载的令牌是否过期
        
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount {
    
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
                return account
            }
            return nil
       }
        
      return NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount
    }
  
    // 归档
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey:"uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    // 反归档
    required init?(coder aDecoder: NSCoder) {
      access_token = aDecoder.decodeObjectForKey("access_token") as! String
      expires_in = aDecoder.decodeObjectForKey("expires_in") as!NSTimeInterval
      uid = aDecoder.decodeObjectForKey("uid")as! String
      expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
      name = aDecoder.decodeObjectForKey("name") as?String
      avatar_large = aDecoder.decodeObjectForKey("avatar_large") as?String
        
    }
    
    // 根据获取的access_token再掉接口获取微博的昵称和头像
    func loadUserInfo(finishedLoad:(account:UserAccount?,error:NSError?)->()){
        
       let params = ["access_token":access_token,"uid":uid]
        
        NetworkTools.sharedNewworkTools().GET("2/users/show.json", parameters: params, success: { (_ , JSON) -> Void in
        
        let dictExtraInfo = JSON as![String:AnyObject]
        
        self.name = dictExtraInfo["name"] as?String
        
        self.avatar_large = dictExtraInfo["avatar_large"] as?String
        
        self.saveAccount()
        
        finishedLoad(account: self, error: nil )
       
        
        }) { (_ , ERROR) -> Void in
            
           finishedLoad(account: nil, error: ERROR)
        }
    }
}

